"""Logging configuration for the application."""
import logging
import os
from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler
from flask import Flask, request, g
import time


def setup_logging(app: Flask):
    """Configure application logging.
    
    Args:
        app: Flask application instance
    """
    # Get log level from config
    log_level_str = app.config.get('LOG_LEVEL', 'INFO')
    log_level = getattr(logging, log_level_str.upper(), logging.INFO)
    
    # Create formatters
    detailed_formatter = logging.Formatter(
        '[%(asctime)s] %(levelname)s in %(module)s (%(pathname)s:%(lineno)d): %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    
    simple_formatter = logging.Formatter(
        '[%(asctime)s] %(levelname)s: %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    
    # Configure root logger
    root_logger = logging.getLogger()
    root_logger.setLevel(log_level)
    
    # Remove existing handlers
    for handler in root_logger.handlers[:]:
        root_logger.removeHandler(handler)
    
    # Console handler (for development and Docker)
    console_handler = logging.StreamHandler()
    console_handler.setLevel(log_level)
    console_handler.setFormatter(simple_formatter)
    root_logger.addHandler(console_handler)
    
    # File handler (for production)
    if not app.config.get('DEBUG', False):
        log_file = app.config.get('LOG_FILE', '/var/log/buyu/app.log')
        log_dir = os.path.dirname(log_file)
        
        # Create log directory if it doesn't exist
        if log_dir and not os.path.exists(log_dir):
            try:
                os.makedirs(log_dir, exist_ok=True)
            except OSError:
                app.logger.warning(f"Could not create log directory: {log_dir}")
        
        try:
            # Rotating file handler (rotates when file reaches 10MB, keeps 10 backups)
            file_handler = RotatingFileHandler(
                log_file,
                maxBytes=10 * 1024 * 1024,  # 10MB
                backupCount=10
            )
            file_handler.setLevel(log_level)
            file_handler.setFormatter(detailed_formatter)
            root_logger.addHandler(file_handler)
            
            # Error log file (only errors and critical)
            error_log_file = log_file.replace('.log', '_error.log')
            error_handler = RotatingFileHandler(
                error_log_file,
                maxBytes=10 * 1024 * 1024,
                backupCount=10
            )
            error_handler.setLevel(logging.ERROR)
            error_handler.setFormatter(detailed_formatter)
            root_logger.addHandler(error_handler)
            
        except (OSError, PermissionError) as e:
            app.logger.warning(f"Could not set up file logging: {e}")
    
    # Configure Flask app logger
    app.logger.setLevel(log_level)
    
    # Log application startup
    app.logger.info("=" * 60)
    app.logger.info(f"Buyu Application Starting")
    app.logger.info(f"Environment: {app.config.get('ENV', 'unknown')}")
    app.logger.info(f"Debug Mode: {app.config.get('DEBUG', False)}")
    app.logger.info(f"Log Level: {log_level_str}")
    app.logger.info("=" * 60)
    
    # Set up request logging
    setup_request_logging(app)


def setup_request_logging(app: Flask):
    """Set up request/response logging.
    
    Args:
        app: Flask application instance
    """
    @app.before_request
    def before_request():
        """Log request details and start timer."""
        g.start_time = time.time()
        
        # Log request
        app.logger.info(
            f"Request: {request.method} {request.path} "
            f"from {request.remote_addr}"
        )
        
        # Log request body for POST/PUT (be careful with sensitive data)
        if request.method in ['POST', 'PUT', 'PATCH']:
            if request.is_json:
                # Don't log passwords or tokens
                data = request.get_json()
                if data:
                    safe_data = {k: v for k, v in data.items() 
                                if k not in ['password', 'token', 'secret']}
                    app.logger.debug(f"Request body: {safe_data}")
    
    @app.after_request
    def after_request(response):
        """Log response details and duration."""
        if hasattr(g, 'start_time'):
            duration = time.time() - g.start_time
            
            # Log response
            app.logger.info(
                f"Response: {response.status_code} "
                f"for {request.method} {request.path} "
                f"({duration:.3f}s)"
            )
            
            # Add response time header
            response.headers['X-Response-Time'] = f"{duration:.3f}s"
        
        return response
    
    @app.errorhandler(Exception)
    def log_exception(error):
        """Log unhandled exceptions."""
        app.logger.error(
            f"Unhandled exception: {error}",
            exc_info=True
        )
        # Re-raise to let Flask handle it
        raise


def get_logger(name: str) -> logging.Logger:
    """Get a logger instance.
    
    Args:
        name: Logger name (usually __name__)
        
    Returns:
        Logger instance
    """
    return logging.getLogger(name)
